package zl.applet.block;
import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JPanel;

//预览面板（显示下一个方块）
public class BaseCanvas extends JPanel
{
	private static final long serialVersionUID = 1L;
	private int rows,cols,boxWidth,boxHeight;		//面板所包含的行。列。及里面每个格子的宽。高。及格子样式
	private Color backColor,frontColor;			//面板的背景色。及前景色
	private Box[][] boxes;		//面板所包含的格子
	
	//构造函数
	public BaseCanvas(int rows,int cols,Color backColor,Color frontColor)
	{
		this.rows = rows;
		this.cols = cols;
		this.backColor = backColor;
		this.frontColor = frontColor;
		this.boxes = new Box[this.rows][this.cols];
		for(int i = 0; i < this.boxes.length; i++)
		{	
			//初始化面板里面所有格子
			for(int j = 0; j < this.boxes[i].length; j++)
			{
				this.boxes[i][j] = new Box(false);
			}
		}
	}
	
	//设置格子样式
	public void setStyle(int style)
	{
		this.reset();		//重置
		int key = Block.KEY;		//移位参数（10000000 00000000）				
		//循环格子的行列。判断哪每个格子时候有颜色。
		/*
		比如现在是方块（11001100 00000000）
				11001100 00000000
					&
				10000000 00000000(key)
					=
				10000000 00000000 结果肯定不为0则此方格为有色(if((style & key) != 0) this.boxes[i][j].setIsColor(true);)
				然后 key >>= 1;则：
				11001100 00000000
					&
				01000000 00000000(key)
					=
				01000000 00000000 结果肯定不为0则此方格为有色
				依次类推。最后就画出每个方块对应的样式
		*/
		for(int i = 0; i < this.boxes.length; i++)
		{
			for(int j = 0; j < this.boxes[i].length; j++)
			{
				if((style & key) != 0)
					this.boxes[i][j].setIsColor(true);
				key >>= 1;
			}
		}
		this.repaint();
	}

	//重写JPanel的paint方法。用来画格子的颜色
	public void paint(Graphics g)
	{
		super.paint(g);
		for(int i = 0; i < this.boxes.length; i++)
		{
			for(int j = 0; j < this.boxes[i].length; j++)
			{
				g.setColor(this.boxes[i][j].getIsColor() ? this.frontColor : this.backColor);
				g.fill3DRect(j*this.boxWidth,i*this.boxHeight,this.boxWidth,this.boxHeight,true);
			}
		}
	}
	
	//计算面板里面包含格子的宽、高
	public void fanning()
	{
		this.boxWidth = this.getSize().width / this.cols;
		this.boxHeight = this.getSize().height / this.rows;
	}

	//重置
	public void reset()
	{
		for(int i = 0; i < this.boxes.length; i++)
		{
			for(int j = 0; j < this.boxes[i].length; j++)
			{
				this.boxes[i][j].setIsColor(false);
			}
		}
		this.repaint();
	}
}